﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using T.FAS.Runtime.Metadata.Entity;

namespace T.FAS.Runtime.Action.SPI
{
    //
    // 摘要:
    //     结果集结构
    [DataContract]
    [JsonConverter(typeof(FasActionCommonResultJsonConverter))]
    public class FasActionCommonResult
    {
        public FasActionCommonResult() { state = "-1"; }
        //
        // 摘要:
        //     返回数据
        [DataMember]
        public object data { get; set; }

        //
        // 摘要:
        //     异常码
        [DataMember]
        public string errcode { get; set; }

        /// <summary>
        /// 数据总条数
        /// </summary>
        [DataMember]
        public int total { get; set; }

        //
        // 摘要:
        //     异常信息
        [DataMember]
        public string errmsg { get; set; }

        //
        // 摘要:
        //     状态 1-成功 0-失败
        [DataMember]
        public string state { get; set; }

    }

    public class FasActionCommonResultJsonConverter : JsonConverter
    {
        public override bool CanRead => true;

        public override bool CanWrite => true;

        public override bool CanConvert(Type objectType)
        {
            return true;
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var dataResult = new FasActionCommonResult();

            JObject jObj = serializer.Deserialize<JObject>(reader);

            dataResult.data = jObj.Value<object>("data");
            dataResult.errcode = jObj.Value<string>("errcode");
            var totalTmp  = jObj.Value<double>("total");
            dataResult.total = (int)totalTmp;
            dataResult.errmsg = jObj.Value<string>("errmsg");
            dataResult.state = jObj.Value<string>("state");
            return dataResult;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var data = value as FasActionCommonResult;

            writer.WriteStartObject();
            writer.WritePropertyName("data"); writer.WriteValue(data.data);
            writer.WritePropertyName("errcode"); writer.WriteValue(data.errcode);
            writer.WritePropertyName("total"); writer.WriteValue(data.total);
            writer.WritePropertyName("errmsg"); writer.WriteValue(data.errmsg);
            writer.WritePropertyName("state"); writer.WriteValue(data.state);
            writer.WriteEndObject();
        }

    }
}
